<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\CardCollection;
use App\Models\CardNum;
use App\Models\CardType;
use App\Models\UserCard;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;

class CardController extends Controller
{
    /**
     * 获取卡列表
     * @param Request $request
     * @return void
     */
    public function lists(Request $request)
    {
        $carddata=CardType::where('status',1)->get();
        return $this->success('success',CardCollection::make($carddata));
   }

    /**
     * 绑定卡
     * @param Request $request
     * @return void
     */
    public function BindCard(Request $request)
    {
        $user=$request->user();
        if (empty($user)){
            return $this->error('获取授权失败');
        }
        $keys=$request->input('drnse','');
        if (empty($keys)){
            return $this->error('密钥缺失');
        }
        $card=CardNum::where('key',$keys)->where('status',0)->first();
        if (empty($card)){
            return $this->error('密钥无效');
        }
        try {
            DB::beginTransaction();
            $card->status=1;
            $rest=(new UserCard())->bindCard($user->id,$card->card_id,$keys);
           if($rest && $card->save()){
               DB::commit();
               return $this->success('绑定成功');
           }else{
               return $this->error('绑定失败');
           }
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }
   }
}
